﻿using System;
using System.Web;
using DataAccess.Models;
using DataAccess.Repository;

namespace KPI
{

	public class KPISiteContext
	{
		//private const Double COOKIEEXPIRES = 1;
		public const string CONST_USERSESSION = "KPI.User";
		public const string CONST_USERSESSIONCOOKIE = "KPI.UserIDCookie";
		public const string CONST_APPTHEMECOOKIE = "KPI.APPTHEME";
		private HttpContext _context = HttpContext.Current;

		private LoginUserInfo _CurrentUser;

		private string _AppTheme;

		private KPISiteContext()
		{
		}

		public static KPISiteContext Current
		{
			get
			{
				if(HttpContext.Current == null)
				{
					return null;
				}

				if(HttpContext.Current.Items["KPISiteContext"] == null)
				{
					KPISiteContext context = new KPISiteContext();
					HttpContext.Current.Items.Add("KPISiteContext", context);

					return context;
				}

				return (KPISiteContext)HttpContext.Current.Items["KPISiteContext"];
			}
		}

		/// <summary>
		/// 取用户访问IP
		/// </summary>
		public string UserHostAddress
		{
			get
			{
				if(HttpContext.Current != null &&
						HttpContext.Current.Request != null &&
						HttpContext.Current.Request.UserHostAddress != null)
					return HttpContext.Current.Request.UserHostAddress;
				else
					return string.Empty;
			}
		}

		public string RequestURL
		{
			get
			{
				var result = string.Empty;

				if(this._context != null && _context.Request != null && _context.Request.Url != null)
				{
					var url = _context.Request.Url;

					result = "http://" + url.Host;

					if(url.Port > 0)
					{
						result += ":" + url.Port.ToString();
					}

					result += "/";
					
					return result;
				}

				return result;
			}
		}

		public LoginUserInfo CurrentUser
		{
			get
			{
				if(_CurrentUser == null)
				{
					var userName = string.Empty;

					if(HttpContext.Current.Request.Cookies[CONST_USERSESSIONCOOKIE] != null && !string.IsNullOrWhiteSpace(HttpContext.Current.Request.Cookies[CONST_USERSESSIONCOOKIE].Value))
					{
						userName = HttpContext.Current.Request.Cookies[CONST_USERSESSIONCOOKIE].Value;
					}
					else if(!string.IsNullOrWhiteSpace(HttpContext.Current.Request.QueryString["username"]))
					{
						userName = HttpContext.Current.Request.QueryString["username"];
					}

					if(!string.IsNullOrWhiteSpace(userName))
					{
						using(var userRep = new UserRepository())
						{
							var u = userRep.GetUser(userName);

							if(u != null)
							{
								var theLoginUserInfo = new LoginUserInfo()
								{
									UserID = u.UserID,
									DeptID = 0,
									DeptName = string.Empty,
									RoleName = u.RoleName,
									UserName = u.UserName,
									UserDisplayName = u.UserDescription
								};

								CurrentUser = theLoginUserInfo;
							}
							else
							{
								var u2 = GetUser2(userName); //userRep.GetUser2(userName);

								if(u2 != null)
								{
									var theLoginUserInfo = new LoginUserInfo()
									{
										UserID = u2.ID,
										//DeptID = u2.DeptId,
										//DeptName = u2.DeptName,
										//RoleName = u.RoleName,
										UserName = u2.UserName,
										UserDisplayName = u2.UserCName
									};

									var theGroup = userRep.GetGroupByName(u2.DeptName);
									if(theGroup != null)
									{
										theLoginUserInfo.DeptID = theGroup.GroupID;
										theLoginUserInfo.DeptName = theGroup.GroupName;
										theLoginUserInfo.RoleName = (u2.IsDocReceiver == 1 ? "unitadministrators" : "visitors");

										CurrentUser = theLoginUserInfo;
									}
									else
									{
										//theLoginUserInfo.RoleName = "visitors";
									}
								}
							}
						}
					}
				}

				return this._CurrentUser;
			}
			set
			{
				var u = value;

				if(u != null)
				{
					this._CurrentUser = value;

					if(this._CurrentUser != null)
					{
						KPISiteContext.SetCookie(CONST_USERSESSIONCOOKIE, u.UserName, this._CurrentUser.LoginExpires);
					}
					else
					{
						KPISiteContext.SetCookie(CONST_USERSESSIONCOOKIE, u.UserName, null);
					}
				}
				else
				{
					KPISiteContext.RemoveCookie(CONST_USERSESSIONCOOKIE);

					KPISiteContext.SetCookie(CONST_USERSESSIONCOOKIE, string.Empty, null);

					if(_CurrentUser != null)
					{
						if(!string.IsNullOrWhiteSpace(_CurrentUser.UserName))
						{
							_context.Cache.Remove(_CurrentUser.UserName);
						}
						this._CurrentUser = null;
					}
				}
			}
		}

		private User2 GetUser2(string userName)
		{
			User2 result = null;

			if(!string.IsNullOrWhiteSpace(userName))
			{
				if(this._context.Cache[userName] == null)
				{
					using(var userRep = new UserRepository())
					{
						result = userRep.GetUser2(userName);

						if(result != null)
						{
							this._context.Cache.Add(userName, result, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 30, 0), System.Web.Caching.CacheItemPriority.Default, null);
						}
					}
				}
				else
				{
					result = this._context.Cache[userName] as User2;
				}
			}

			return result;
		}

		public string AppTheme
		{
			get
			{
				if(string.IsNullOrWhiteSpace(_AppTheme))
				{
					if((HttpContext.Current.Request.Cookies[CONST_APPTHEMECOOKIE] != null) && !(string.IsNullOrEmpty(HttpContext.Current.Request.Cookies[CONST_APPTHEMECOOKIE].Value)))
					{
						_AppTheme = HttpContext.Current.Request.Cookies[CONST_APPTHEMECOOKIE].Value;
					}
					else
					{
						_AppTheme = "default";
					}
				}

				return _AppTheme;
			}
			set
			{
				_AppTheme = value;

				KPISiteContext.SetCookie(CONST_APPTHEMECOOKIE, _AppTheme, DateTime.Now.AddMonths(6));
			}
		}

		/// <summary>
		/// Gets or sets an object item in the context by the specified key.
		/// </summary>
		/// <param name="key">The key of the value to get.</param>
		/// <returns>The value associated with the specified key.</returns>
		public object this[string key]
		{
			get
			{
				if(this._context == null)
				{
					return null;
				}

				if(this._context.Items[key] != null)
				{
					return this._context.Items[key];
				}

				return null;
			}
			set
			{
				if(this._context != null)
				{
					this._context.Items.Remove(key);
					this._context.Items.Add(key, value);
				}
			}
		}

		/// <summary>
		/// 设置 cookie
		/// </summary>
		/// <param name="key">Key</param>
		/// <param name="val">Value</param>
		public static void SetCookie(string key, string val, DateTime? expires)
		{
			if(Current != null)
			{
				HttpCookie cookie = new HttpCookie(key);
				cookie.Value = val;

				//if(string.IsNullOrEmpty(val))
				//{
				//  cookie.Expires = DateTime.Now.AddMonths(-1);
				//}
				//else
				//{
				//  cookie.Expires = DateTime.MinValue;
				//}
				if(expires.HasValue)
				{
					cookie.Expires = expires.Value;
				}
				else
				{
					cookie.Expires = DateTime.MinValue;
				}

				HttpContext.Current.Response.Cookies.Remove(key);
				HttpContext.Current.Response.Cookies.Add(cookie);
			}
		}

		/// <summary>
		/// 获取 cookie
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public static string GetCookie(string key)
		{
			var result = string.Empty;

			if(HttpContext.Current.Request.Cookies[key] != null && !string.IsNullOrEmpty(HttpContext.Current.Request.Cookies[key].Value))
			{
				result = HttpContext.Current.Request.Cookies[key].Value;
			}

			return result;
		}

		/// <summary>
		/// 移除 cookie
		/// </summary>
		/// <param name="key"></param>
		public static void RemoveCookie(string key)
		{
			if(Current != null)
			{
				HttpContext.Current.Response.Cookies.Remove(key);
				HttpContext.Current.Request.Cookies.Remove(key);
			}
		}
	}
}